﻿using Newtonsoft.Json;
using System.Diagnostics;

namespace TestModel.Model
{
    /// <summary>
    /// Json资源类
    /// </summary>
    /// <typeparam name="T">映射的类</typeparam>
    public class JsonAccess<T> : LocalAccess<T>
    {
        public JsonAccess(string path) : base(path)
        {
        }

        public override void Load()
        {
            string data = File.ReadAllText(Path);
            List<T>? datas = JsonConvert.DeserializeObject<List<T>>(data);
            if (datas == null)
            {
                MessageBox.Show($"加载数据文件失败，文件地址：{Path}");
            }
            else
            {
                Access = datas;
                Debug.Print(string.Format("加载数据成功，共加载[{0}]条数据", Access.Count));
            }

        }

        public override void Save()
        {
            if (Access != null && Access.Count > 0)
            {
                string result = JsonConvert.SerializeObject(Access);
                File.WriteAllText(Path, result);
                Debug.Print(string.Format("保存[{0}]条数据成功!", Access.Count));
            }
            else
            {
                Debug.Print("文件为空,无需保存");
            }
        }

    }
}
